<template>
    <div class="uploads_class">
        <a-row>
            <a-space>
                <div>
                    <span>项目年份:</span>
                    <a-select 
                    v-model:value="year"
                    style="width: 150px;"
                    :options="years"
                    size="small"
                    :field-names="{ label: 'year', value: 'year' }"
                    @change="year_change"
                    >
                    </a-select>
                </div>
                <div>
                    <a-button @click="add_year" style="margin: 0 auto;">
                        添加年份
                    </a-button>
                </div>
                <div>
                    <a-button @click="add_pro" style="margin: 0 auto;">
                        添加项目
                    </a-button>
                </div>
                <div>
                    <a-button @click="search_pro" style="margin: 0 auto;">
                        查询
                    </a-button>
                </div>
            </a-space>
        </a-row>
        <a-row style="margin-top: 5px;">
            <a-collapse v-model:activeKey="collapse_activeKey" accordion  expand-icon-position="left" style="width:100%" @change="pro_select_change">
                    <a-collapse-panel  :header="item?.name" :key="item?._id" v-for="item in pros" >
                        <template #extra>
                            <a-space size="large">
                                <!-- <a-tooltip  placement="right">
                                    <template #title>编辑项目</template>
                                    <setting-outlined @click="edit_pro" />
                                </a-tooltip> -->
                                <a-tooltip  placement="right" v-if="($store?.state?.user?$store?.state?.user?.type:-1)>=1">
                                    <template #title>删除项目</template>
                                    <a-popconfirm 
                                        title="确定删除此类别吗?"
                                        ok-text="确定"
                                        cancel-text="取消"
                                        @confirm="delete_pro(item)"
                                        >
                                            <delete-outlined   @click="delete_pro_pre"/>
                                        </a-popconfirm>
                                </a-tooltip>
                            </a-space>
                        </template>
                        <a-row>
                            <a-space>
                                <div>
                                    <a-button @click="add_pro_frist_group" style="margin: 0 auto;">
                                        添加一级类别
                                    </a-button>
                                </div>
                                <div>
                                    <a-button @click="add_pro_frist_file" style="margin: 0 auto;">
                                        添加一级文件
                                    </a-button>
                                </div>
                            </a-space>
                        </a-row>
                        <a-row style="overflow-y: scroll;height: 420px;">
                            <a-col :span="14">
                                <a-directory-tree
                                    :tree-data="groups"
                                    @select="pro_group_select"
                                    :fieldNames="pro_group_fieldnames"
                                    class="org-tree"
                                    >
                                    <template #icon="{ dataRef}">
                                        <folder-filled style="width: 18px;" v-if="dataRef?.type=='dir'"/>
                                        <file-filled style="width: 18px;" v-if="dataRef?.type=='file'"/>
                                    </template>
                                    <template #title="{dataRef}">
                                        <a-dropdown :trigger="['contextmenu']">
                                            <span>{{dataRef?.name}}</span>
                                            <template #overlay>
                                                <a-menu @click="({ key: menuKey }) => tree_contextmenu(menuKey,dataRef)">
                                                    <a-menu-item key="edit_child_group" >重命名</a-menu-item>
                                                    <a-menu-item key="add_child_group" v-if="dataRef?.type=='dir'">添加下级类别</a-menu-item>
                                                    <a-menu-item key="delete_child_group" v-if="dataRef?.type=='dir'">
                                                        <a-popconfirm 
                                                        title="确定删除此类别吗?将删除当前和子节点的所有文件?"
                                                        ok-text="确定"
                                                        cancel-text="取消"
                                                        @confirm="delete_child_group(dataRef)"
                                                        v-if="($store?.state?.user?$store?.state?.user?.type:-1)>=1"
                                                        >
                                                            <a href="javascript:;">删除类别</a>
                                                        </a-popconfirm>
                                                    </a-menu-item>
                                                    <a-menu-item key="add_child_file" v-if="dataRef?.type=='dir'">添加文件</a-menu-item>
                                                    <a-menu-item key="delete_child_file" v-if="dataRef?.type=='file'">
                                                        <a-popconfirm 
                                                        title="确定删除此类别吗?"
                                                        ok-text="确定"
                                                        cancel-text="取消"
                                                        @confirm="delete_child_file(dataRef)"
                                                        v-if="($store?.state?.user?$store?.state?.user?.type:-1)>=1"
                                                        >
                                                            <a href="javascript:;">删除文件</a>
                                                        </a-popconfirm>
                                                    </a-menu-item>
                                                </a-menu>
                                            </template>
                                        </a-dropdown>
                                    </template>
                                </a-directory-tree> 
                            </a-col>
                            <!-- <a-col :span="0"></a-col> -->
                            <a-col :span="10">
                                <a-descriptions title="" bordered :column="1" size="small">
                                    <a-descriptions-item label="项目">{{ get_pro_by_id(pro_group_select_node?.pro)?.name }}</a-descriptions-item>
                                    <a-descriptions-item label="项目层级">{{ get_group_by_id(pro_group_select_node?.pre)?.name }}</a-descriptions-item>
                                    <a-descriptions-item label="文件名称">{{ pro_group_select_node?.name }}</a-descriptions-item>
                                    <a-descriptions-item label="文件大小">{{ $common_apis.FormatFileSize(pro_group_select_node?.size) }}</a-descriptions-item>
                                    <a-descriptions-item label="文件上传时间">{{ $common_apis.GetTime(pro_group_select_node?.uptime) }}</a-descriptions-item>
                                    <a-descriptions-item label="文件上传人">{{ pro_group_select_node?.user }}</a-descriptions-item>
                                    <a-descriptions-item label="文件保存地址">
                                        <a-row >
                                            <a-col :span="20">
                                                <div>{{ pro_group_select_node?.dir }}</div>
                                            </a-col>
                                            <a-col :span="4">
                                                <a-button @click="download_file" style="margin: 0 auto;"  size="small" v-if="pro_group_select_node">下载</a-button>
                                            </a-col>
                                        </a-row>
                                    </a-descriptions-item>
                                    <!-- <a-descriptions-item label="下载文件">{{ pro_group_select_node?.dir }}</a-descriptions-item> -->
                                </a-descriptions>
                            </a-col>
                        </a-row>
                    </a-collapse-panel>
            </a-collapse>
        </a-row>
        <!-- 添加年份 -->
        <a-modal 
        class="my-modal short" 
        v-model:visible="add_year_modal_show" 
        title="添加年份" 
        @ok="add_year_ok" 
        width="400px" 
        :maskClosable="false" 
        :centered="true"
        :destroyOnClose="true"
        >
            <div class="body-content">
                <a-input size="small" placeholder="" v-model:value="ad_year" />
            </div>
        </a-modal>
        <!-- 添加项目 -->
        <a-modal 
        class="my-modal short" 
        v-model:visible="add_pro_modal_show" 
        title="添加项目" 
        @ok="add_pro_ok" 
        width="400px" 
        :maskClosable="false" 
        :centered="true"
        :destroyOnClose="true"
        >
            <a-form
            :model="pro"
            name="basic"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 18 }"
            autocomplete="off"
            >
                <a-form-item label="年份">
                    <a-col :span="22">
                        <a-input  v-model:value="year"  disabled/> 
                    </a-col>
                </a-form-item>
                <a-form-item label="名称">
                    <a-col :span="22">
                        <a-input  v-model:value="pro.name"/> 
                    </a-col>
                </a-form-item>
                <a-form-item label="描述">
                    <a-col :span="22">
                        <a-input  v-model:value="pro.description"/> 
                    </a-col>
                </a-form-item>
             </a-form>
        </a-modal>
        <!-- 添加类别 -->
        <a-modal 
        class="my-modal short" 
        v-model:visible="add_pro_frist_group_show" 
        title="添加类别" 
        @ok="add_pro_frist_group_ok" 
        width="400px" 
        :maskClosable="false" 
        :centered="true"
        :destroyOnClose="true"
        >
            <a-form
            :model="pro_group"
            name="basic"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 18 }"
            autocomplete="off"
            >
                <a-form-item label="上级类别">
                    <a-col :span="22">
                        <a-input  v-model:value="pro_group.pre" disabled/> 
                    </a-col>
                </a-form-item>
                <a-form-item label="类别名称">
                    <a-col :span="22">
                        <a-input  v-model:value="pro_group.name"/> 
                    </a-col>
                </a-form-item>
             </a-form>
        </a-modal>
         <!-- 修改类别 -->
         <a-modal 
        class="my-modal short" 
        v-model:visible="edit_group_show" 
        title="添加类别" 
        @ok="edit_group_ok" 
        width="400px" 
        :maskClosable="false" 
        :centered="true"
        :destroyOnClose="true"
        >
            <a-form
            :model="pro_group"
            name="basic"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 18 }"
            autocomplete="off"
            >
                <a-form-item label="类别名称">
                    <a-col :span="22">
                        <a-input  v-model:value="edit_group.name"/> 
                    </a-col>
                </a-form-item>
             </a-form>
        </a-modal>
        <!-- 添加文件 -->
        <a-modal 
        class="my-modal short" 
        v-model:visible="add_file_modal_show" 
        title="添加文件" 
        @ok="add_file_ok" 
        width="400px" 
        :maskClosable="false" 
        :centered="true"
        :destroyOnClose="true"
        >
        <!-- :maxCount="1" -->
            <a-upload-dragger
            v-model:fileList="fileList"
            name="file"
            :multiple="true"
            :action="upload_url"
            :before-upload="before_upload"
            @change="upload_change"
            :data="upload_data"
            
            >
                <p class="ant-upload-drag-icon">
                <inbox-outlined></inbox-outlined>
                </p>
                <p class="ant-upload-text">点击或拖动文件到此区域进行上传</p>
                <p class="ant-upload-hint">支持大部分文件</p>
            </a-upload-dragger>
        </a-modal>
    </div>
</template>
<script>
import { defineAsyncComponent } from 'vue'
    export default {
        data() {
            return {
                year:"",//seclet 选中的年份
                years:[], //所有的年份
                ad_year:"", //添加年份
                add_year_modal_show:false,//添加年份显示
                pros:[], //当前年份的所有项目
                add_pro_modal_show:false,//添加项目线索
                pro:{ //添加项目属性对象
                    name:"",
                    description:"",
                },
                collapse_activeKey:"", //项目的collapse_activeKey
                select_pro_id:"", //当前激活的项目id
                groups_only:[],//项目的group树形结构
                groups:[],//项目的group 文件树形结构和
                pro_group_fieldnames:{ //项目的group树形结构的属性配置
                    children:'children',
                    title:'name', 
                    key:'_id'
                },
                pro_group_select_node:undefined,//鼠标选中tree的node
                add_pro_frist_group_show:false,//显示 添加group
                pro_group:{ //添加group的对象
                    pre:"root",
                    name:"",
                },
                edit_group_show:false,
                edit_group:{ //编辑group的对象
                    id:"",
                    name:"",
                },
                upload_node:undefined,//上传时选中的group node
                add_file_modal_show:false, //显示上传控件
                fileList:[],//上传list
                upload_url:"",//上传url
                upload_data:{ //上传额外值
                    name:"", //上传文件名
                },
            }
        },
        mounted() {
            this.upload_url=`${window.server_url}/pro_upload/upload`
            this.get_years()
            document.oncontextmenu=(event)=>{
                event.stopPropagation();
                return false;
            }
        },
        components: {
            // uploading: defineAsyncComponent(() => import("./uploading.vue")),
            // myfiles: defineAsyncComponent(() => import("./myfiles.vue")),
            // myshare: defineAsyncComponent(() => import("./myshare.vue")),
            // allshare: defineAsyncComponent(() => import("./allshare.vue")),
        },
        methods:{
            year_change(value){
                this.search_pro()
            },
            add_year(){
                this.add_year_modal_show=true
            },
            async add_year_ok(){
                let result=await this.$apis.get_year({
                    year:this.ad_year
                })
                if(result){
                    this.get_years()
                }

                this.add_year_modal_show=false
            },
            async get_years(){
                let result=await this.$apis.get_year()
                if(result){
                    result=Array.from(new Set(result))
                    result.sort((a,b)=>{
                        return b.year-a.year
                    })
                    if(result?.length){
                        this.year=result[0].year
                    }
                    this.years=result
                    this.ad_year=""
                    this.collapse_activeKey="";
                }
            },
            add_pro(){
                this.add_pro_modal_show=true
            },
            async add_pro_ok(){
                this.pro.year=this.year
                let result=await this.$apis.add_pro(this.pro)
                if(result){
                    this.search_pro()
                }
                this.add_pro_modal_show=false
            },
            async search_pro(){
                let result=await this.$apis.get_pro({
                    year:this.year
                })
                if(result){
                    this.pros=result
                }
            },
            get_pro_by_id(id){
                return this.pros.find((val)=>{
                    return val["_id"]==id
                })
            },
            edit_pro(){
                console.log("edit_pro")
            },
            delete_pro_pre(event){
                event.stopPropagation();
            },
            async delete_pro(item){
                let result=await this.$apis.delete_pro({
                    id:item["_id"]
                })
                if(result){
                    this.search_pro()
                }
            },
            async pro_select_change(id){
                this.select_pro_id=id
                if(id){
                    this.get_group()
                }
                else{
                    this.groups=[]
                }
            },
            async get_group(){
                this.groups_only=[]
                let result=await this.$apis.get_group({
                    pro:this.select_pro_id
                })
                let result2=await this.$apis.get_file({
                    pro:this.select_pro_id
                })
                if(result){
                    this.groups_only=result
                    for (let i = 0; i < result.length; i++) {
                        result[i].type="dir"
                    }
                    for (let i = 0; i < result2.length; i++) {
                        result2[i].type="file"
                    }
                    let new_new_result=[].concat(result,result2)
                    let new_new_result2=this.array_to_tree(new_new_result)
                    this.groups=new_new_result2
                }
            },
            array_to_tree(data){
                let result = []
                let map = {}
                data.forEach(item => {map[item["_id"]] = item})
                data.forEach(item => {
                    let parent = map[item["pre"]] //找到data中每一项item的爸爸
                    if (parent) {
                        (parent.children || (parent.children = [])).push(item)
                    } else {
                        result.push(item) //item是对象的引用
                    }
                })
                return result
            },
            tree_to_array(tree){
                let _array=[]
                for (let i = 0; i < tree?.length; i++) {
                    let one_root_work = tree[i];
                    let new_one_root_work=JSON.parse(JSON.stringify(one_root_work))
                    delete new_one_root_work.children
                    _array.push(new_one_root_work)
                    if(one_root_work?.children){
                        let children=this.tree_to_array(one_root_work.children)
                        _array=_array.concat(children)
                    }
                }
                return _array;
            },
            get_group_by_id(pre){
                return this.groups_only.find((val)=>{
                    return val["_id"]==pre
                })
            },
            add_pro_frist_group(){
                this.add_pro_frist_group_show=true;
                this.pro_group.pre="root"
                this.pro_group.name=""
            },
            async delete_child_group(dataRef){
                let array_data=this.tree_to_array([dataRef])
                let groups=array_data.filter((val)=>{
                    return val.type=="dir"
                })
                let files=array_data.filter((val)=>{
                    return val.type=="file"
                })
                for (let i = 0; i < groups.length; i++) {
                    await this.$apis.delete_group({
                        id:groups[i]["_id"]
                    })
                }
                for (let i = 0; i < files.length; i++) {
                    await this.$apis.delete_file({
                        id:files[i]["_id"]
                    })
                }
                this.get_group()
            },
            async delete_child_file(dataRef){
                let result=await this.$apis.delete_file({
                    id:dataRef["_id"]
                })
                if(result){
                    this.get_group()
                }
            },
            async add_pro_frist_group_ok(){
                let new_pro_group=JSON.parse(JSON.stringify(this.pro_group))
                new_pro_group.pro=this.select_pro_id
                let result=await this.$apis.add_group(new_pro_group)
                if(result){
                    this.get_group()
                }
                this.add_pro_frist_group_show=false;
            },
            add_pro_frist_file(){
                this.upload_node={
                    pro: this.select_pro_id,
                    _id: "",
                }
                this.add_file()
            },
            async tree_contextmenu(menuKey,dataRef){
                if(menuKey=="add_child_group"){
                    this.pro_group.pre=dataRef["_id"]
                    this.pro_group.name=""
                    this.add_pro_frist_group_show=true;
                }
                else if(menuKey=="edit_child_group"){
                    this.edit_group.id=dataRef["_id"]
                    this.edit_group.name=dataRef?.name
                    this.edit_group_show=true;
                }
                else if(menuKey=="add_child_file"){
                    this.upload_node=dataRef
                    this.add_file()
                }
                else if(menuKey=="delete_child_file"){
                    return
                }
                else if(menuKey=="delete_child_group"){
                    return
                }
            },
            async edit_group_ok(){
                if(!this.edit_group.name){
                    this.$message.info("输入类别名称")
                    return
                }
                let result=await this.$apis.edit_group(this.edit_group)
                if(result){
                    this.edit_group_show=false;
                    this.get_group()
                }
            },
            pro_group_select(selectedKeys,{selectedNodes}){
                let select_node=selectedNodes[0]
                if(select_node?.type=="file"){
                    this.pro_group_select_node=select_node
                }
                else{
                    this.pro_group_select_node=undefined
                }
            },
            add_file(){
                this.add_file_modal_show=true
                this.fileList=[]
            },
            async add_file_ok(){
                this.add_file_modal_show=false
            },
            before_upload(file, fileList){
                this.upload_data.name=file.name
                return true
            },
            upload_change(changes){
                if(changes?.file?.status=="done" && changes?.file?.response?.status==true){
                    this.add_file_core(changes?.file?.response?.file,changes?.file?.size)
                    this.add_file_modal_show=false
                    // this.fileList=[]
                }
            },
            async add_file_core(file_full_path,file_size){
                let file_prop={
                    pro:this.upload_node?.pro,
                    pre:this.upload_node["_id"],
                    dir:file_full_path,
                    size:file_size
                }
                let result=await this.$apis.add_file(file_prop)
                if(result){
                    this.get_group()
                }
            },
            download_file(){
                let _href = `${window.server_url}/change/down_file?file=${this.pro_group_select_node?.dir}`
                window.open(_href, '_blank');
            },

        }
  }
</script>